import React, { useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'dva';
import { Form, AutoComplete, Input, Button, Transfer, Tree } from 'antd';
import { Icon } from 'react-fa';
import Tabs from '@/components/Tabs/Tabs';
import Grid from '@/components/Grid';
import Layout from '@/components/Layout';
import Dialog from '@/components/Dialog';
import settings, { getPagination } from '@/settings';
// import Authorized, { checkRouteAuth } from '@/components/Authorized';
import { getQueryKeywords, createAction } from '@/utils';
import { check } from '@/services/user';
import { search, getNodes } from '@/services/group';
import api from '@/api'

const { TreeNode } = Tree;

const ModelForm = Form.create()(props => {
  const dispatch = useDispatch()
  
  const [activeKey, setActiveKey] = useState("1")
  const [expandedKeys, setExpandedKeys] = useState([])
  const [confirmDirty, setConfirmDirty] = useState(false)
  // const [selectedKeys, setSelectedKeys] = useState([])

  const { 
    roleIds = [],
    data = {},
    roles = [],
    groups = [],
    groupIds = [],
    groupPaths = []
  } = useSelector(_ => _.user)

  if (groupPaths.length) {
    const paths = groupPaths.flatMap(_ => _.split('/'))
    setExpandedKeys(paths)
    dispatch(createAction('user/updateState')({
      groupIds: groupPaths.map(_ => _.split('/')[_.split('/').length - 1]),
    }));
  }

  const {
    id,
    form: { getFieldValue, validateFields, getFieldDecorator }
  } = props

  useEffect(() => {
    if (id) {
      dispatch(createAction('user/fetchOne')({
        id
      }));
    }
  }, [dispatch, id]);

  useEffect(() => {
    dispatch(createAction('user/fetchGroups')());
    dispatch(createAction('user/fetchRoles')());
  }, [dispatch]);

  const handleSubmit = (_, callback) => {
    validateFields((err, values) => {
      if (err) {
        setActiveKey("1")
      } else {
        callback({
          ...values,
          roleId: roleIds,
          groupId: groupIds[0]
        });
      }
    });
  };

  props.register(handleSubmit)

  const handleChange = targetKeys => {
    dispatch(createAction('user/updateState')({
      roleIds: targetKeys,
    }));
  };
  const handleConfirmBlur = e => {
    const value = e.target.value;

    setConfirmDirty(confirmDirty || !!value)
  };
  const compareToFirstPassword = (rule, value, callback) => {
    if (value && value !== getFieldValue('pwd')) {
      callback('两次输入的密码不一致');
    } else {
      callback();
    }
  };
  const validateToNextPassword = (rule, value, callback) => {
    if (value && confirmDirty) {
      validateFields(['confirmPassword'], {
        force: true,
      });
    }
    callback();
  };
  const renderTreeNodes = (data = []) =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} selectable={false} key={item.id} dataRef={item} icon={<Icon name="folder-open" />}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return (
        <TreeNode {...item} title={item.name} selectable={false} key={item.id} dataRef={item} icon={<Icon name="folder-open" />} />
      );
    });
  const onCheck = (checkedKeys, { checked, node }) => {
    let _checkedKeys = []
    if (checked) {
      _checkedKeys = [node.props.dataRef.id]
    }
    dispatch(createAction('user/updateState')({
      groupIds: _checkedKeys
    }));
  };
  // const onSelect = (selectedKeys, { selected, node }) => {
  //   let _checkedKeys = []
  //   if (selected) {
  //     _checkedKeys = [node.props.id]
  //   }
  //   dispatch(createAction('user/updateState')({
  //     groupIds: _checkedKeys
  //   }));
  // };
  const onExpand = expandedKeys => {
    setExpandedKeys(expandedKeys)
  }
  const onLoadData = async treeNode => {
    if (!treeNode.props.children) {
      const { data } = await getNodes({
          id: treeNode.props.id
      })
      treeNode.props.dataRef.children = data

      dispatch(createAction('user/updateState')({
        groups: [...groups]
      }))
    }
  }
  const onChange = activeKey => {
    setActiveKey(activeKey)
  }

  const [groupOptions, setGroupOptions] = useState([])

  const handleOptionSelect = (value, option) => {
    const ids = value.split('/')

    setExpandedKeys(ids)
  }
  const renderOption = item => {
    const { name, names } = getQueryKeywords(item.s, item.name)

    return (
      <AutoComplete.Option key={item.path} text={name}>
        <span dangerouslySetInnerHTML={{__html: names}}></span>
      </AutoComplete.Option>
    )
  }
  const searchResult = (s, data) => (data || []).map(item => ({
    ...item,
    s
  }))
  const handleTreeSearch = async value => {
    if (value) {
      const data = await search({
        s: value
      })
      setGroupOptions(searchResult(value, data))
    } else {
      setGroupOptions([])
    }
  }

  return (
    <Tabs activeKey={activeKey} layout="fixed" onChange={onChange}>
      <Tabs.TabPane tab="用户信息" key="1">
        <Form layout="vertical">
          <Form.Item label="用户名">
            {getFieldDecorator('name', {
              validateFirst: true,
              rules: [
                {
                  required: true,
                  message: '请输入用户名',
                },
                {
                  validator: async (rule, value, callback) => {
                    if (!value || value.trim() === '' || (data.name && data.name.trim() === value.trim())) return callback()
                    // await dispatch(createAction('user/valid')({
                    //   id,
                    //   value
                    // }));
                    // valid ? callback() : callback('用户名已存在');
                    
                    const invalid = await check({
                          [settings.valid]: value,
                        })
                    invalid ? callback('用户名已存在') : callback();
                  },
                },
              ],
              initialValue: data.name,
            })(<Input placeholder="请输入" />)}
          </Form.Item>
          {!id && (
            <React.Fragment>
              <Form.Item label="密码">
                {getFieldDecorator('pwd', {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                    {
                      validator: validateToNextPassword,
                    },
                  ],
                })(<Input.Password placeholder="请输入" />)}
              </Form.Item>
              <Form.Item label="确认密码">
                {getFieldDecorator('confirmPassword', {
                  rules: [
                    {
                      required: true,
                      message: '请输入密码',
                    },
                    {
                      validator: compareToFirstPassword,
                    },
                  ],
                })(<Input.Password placeholder="请输入" onBlur={handleConfirmBlur} />)}
              </Form.Item>
            </React.Fragment>
          )}
          <Form.Item label="用户姓名">
            {getFieldDecorator('title', {
              rules: [{
                required: true,
                message: '请输入用户姓名'
              }],
              initialValue: data.title,
            })(<Input placeholder="请输入" />)}
          </Form.Item>
          <Form.Item label="联系电话">
            {getFieldDecorator('currentMobile', {
              rules: [
                {
                  required: true,
                  pattern: /^\d{11}$/,
                  message: '请输入十一位手机号码',
                },
              ],
              initialValue: data.currentMobile,
            })(<Input placeholder="请输入" />)}
          </Form.Item>
          {/*<Form.Item label="email">
            {getFieldDecorator('email', {
              rules: [
                {
                  type: 'email',
                  message: '请输入正确的电子邮箱',
                },
              ],
              initialValue: data.email,
            })(<Input placeholder="请输入" />)}
          </Form.Item>*/}
        </Form>
      </Tabs.TabPane>
      <Tabs.TabPane tab="所属角色" key="2">
        <Transfer
          rowKey={record => record.id}
          showSearch
          dataSource={roles}
          listStyle={{
            width: 210,
            height: 340,
          }}
          // showSearch
          // filterOption={filterOption}
          targetKeys={roleIds}
          onChange={handleChange}
          render={item => item.name}
        />
      </Tabs.TabPane>
      <Tabs.TabPane tab="所属部门" key="3">
        <div className="x-query fixed">
          <AutoComplete
            dataSource={groupOptions.map(renderOption)}
            onSelect={handleOptionSelect}
            onSearch={handleTreeSearch}
            placeholder="请输入部门名称"
            optionLabelProp="text"
          >
            <Input suffix={<Icon name="search" />} />
          </AutoComplete>
        </div>
        <Tree
          checkable
          // multiple
          showIcon
          loadData={onLoadData}
          checkedKeys={groupIds}
          expandedKeys={expandedKeys}
          onExpand={onExpand}
          // selectedKeys={selectedKeys}
          checkStrictly
          rowKey={record => record.id}
          onCheck={onCheck}
          // onSelect={onSelect}
        >
          {renderTreeNodes(groups)}
        </Tree>
      </Tabs.TabPane>
    </Tabs>
  );
})

const UserPage = props => {
  const dispatch = useDispatch()
  const [selectedRows, setSelectedRows] = useState([])
  const { list = {}, params = {} } = useSelector(_ => _.user)
  const { data, total } = list
  const { effects } = useSelector(_ => _.loading)
  const loading = effects['user/fetchList']

  const columns = [
    {
      title: '用户名',
      dataIndex: 'name',
    },
    {
      title: '真实姓名',
      dataIndex: 'title',
      align: 'center',
    },
    // {
    //   title: '所属部门',
    //   dataIndex: 'groupLabel'
    // },
    {
      title: '手机号码',
      dataIndex: 'currentMobile',
      align: 'center',
    },
    {
      title: '是否锁定',
      dataIndex: 'valid',
      align: 'center',
      render: (v, record, index) => {
        return (
          v === 1 ? <span className="text-info">正常</span> : <span className="text-danger">已锁定</span>
        )
      }
    },
    // {
    //   title: '操作',
    //   dataIndex: 'id',
    //   width: 200,
    //   align: 'center',
    //   render: (v, record, index) => {
    //     return (
    //       <React.Fragment>
    //         <span
    //           className="btn-text text-info" onClick={e => handleMenuEvent(e, 'lock', v)}>
    //           <Icon
    //             name="unlock"
    //           />
    //           锁定
    //         </span>
    //       </React.Fragment>
    //     )
    //   }
    // },
  ];

  useEffect(() => {
    dispatch(createAction('user/fetchList')());
  }, [dispatch]);

  const handleSelectRows = rows => {
    setSelectedRows(rows)
  };
  // const handleMenuEvent = (e, key, id) => {
  //   e.stopPropagation()

  //   switch (key) {
  //     case 'lock':
  //       handleLock(e, id)
  //       break
  //     case 'unlock':
  //       handleUnLock(e, id)
  //       break
  //     default :
  //   }
  // };
  const handleLock = (e, id) => {
    if (id === undefined) {
      id = selectedRows[0].id;
    }
    Dialog.confirm({
      title: '确认提示',
      content: '确定要锁定当前用户？',
      onOk: async () => {
        await dispatch(createAction('user/lock')({
          id: [id]
        }))
        handleReload();
      },
    });
  }
  const handleUnLock = (e, id) => {
    if (id === undefined) {
      id = selectedRows[0].id;
    }
    Dialog.confirm({
      title: '确认提示',
      content: '确定要解锁当前用户？',
      onOk: async () => {
        await dispatch(createAction('user/unlock')({
          id: [id]
        }))
        handleReload();
      },
    });
  }
  const handleAdd = e => {
    dispatch(createAction('user/reset')());
    Dialog.open({
      title: '新建用户',
      fixed: true,
      effect: true,
      component: ModelForm,
      url: api.user_add,
      onOk: data => {
        handleReload();
      },
      connect: ({ loading }) => ({
              loading: loading.effects['user/fetchGroups'] && loading.effects['user/fetchRoles'],
            })
    });
  };
  const handleEdit = e => {
    const { id } = selectedRows[0];
    dispatch(createAction('user/reset')());
    Dialog.open({
      title: '修改用户',
      fixed: true,
      effect: true,
      url: api.user_update,
      data: {
        id,
      },
      // options: {
      //   type: 'put',
      // },
      onOk: data => {
        handleReload();
      },
      component: props => <ModelForm {...props} id={id} />,
      connect: ({ loading }) => ({
        loading:
          loading.effects['user/fetchGroups'] && loading.effects['user/fetchRoles'] && loading.effects['user/fetchOne'],
      }),
    });
  };
  const handleRemove = e => {
    Dialog.confirm({
      title: '确认提示',
      content: '确定要删除已选择的用户？',
      onOk: async () => {
        await dispatch(createAction('user/delete')({
          id: selectedRows.map(_ => _.id)
        }))
        handleReload();
      },
    });
  };
  const handleGridChange = (oldPagination, sorter) => {
    const pagination = getPagination(oldPagination);
    const payload = {
      ...params,
      ...pagination,
    };

    if (sorter.field) {
      payload.sorter = sorter.field;
      payload.order = sorter.order;
    }

    dispatch(createAction('user/fetchList')(payload));
  };
  const handleReload = () => {
    dispatch(createAction('user/fetchList')(params));
  };
  const handleSearch = (value, e) => {
    e.preventDefault();
    const pagination = getPagination({
      pageNumber: 1,
    });
    dispatch(createAction('user/fetchList')({
      ...params,
      ...pagination,
      title: value,
    }));
  };

  const pageNumber = params[settings.pageNumber];
  return (
    <Layout
      toolbar={{
        left: (
          <React.Fragment>
            <Button.Group>
              <Button type="primary" onClick={handleAdd}>
                新建
              </Button>
              <Button onClick={handleEdit} disabled={selectedRows.length !== 1}>
                编辑
              </Button>
              <Button
                type="danger"
                disabled={selectedRows.length === 0}
                onClick={handleRemove}
              >
                删除
              </Button>
            </Button.Group>
            <Button.Group>
              <Button
                disabled={selectedRows.filter(_ => _.valid === 1).length === 0}
                onClick={handleLock}
              >
                锁定
              </Button>
              <Button
                disabled={selectedRows.filter(_ => _.valid === 0).length === 0}
                onClick={handleUnLock}
              >
                解锁
              </Button>
            </Button.Group>
          </React.Fragment>
        ),
        right: (
          <Form layout="inline">
            <Input.Search placeholder="请输入用户名或姓名" onSearch={handleSearch} />
            {/*<Button onClick={showSearchPanel}>高级查询</Button>*/}
          </Form>
        ),
      }}
    >
      <Grid
          selectedRows={selectedRows}
          onSelectRow={handleSelectRows}
          // rowSelection={{
          //   type: 'radio'
          // }}
          columns={columns}
          data={data}
          loading={loading}
          pagination={{
            pageNumber,
            total,
          }}
          onReload={handleReload}
          onChange={handleGridChange}
        />
    </Layout>
  );
}

export default UserPage;
